package steampunk.utils;

import java.util.Hashtable;

/**
 * This is a table that maintains a count of the items put in it (rather
 * than storing copies of the items themselves).
 * @author garrett
 *
 * @param <T>
 */
public class CountTable<T> {

	private Hashtable<T, Integer> counts;
	
	public CountTable() {
		counts = new Hashtable<T, Integer>();
	}
	
	/**
	 * Increments the count of the given item
	 * @param t
	 */
	public void add(T t) {
		if (!counts.containsKey(t)) {
			counts.put(t, 1);
		} else {
			counts.put(t, counts.get(t)+1);
		}
	}
	
	/**
	 * Returns the count of the given item (or 0 if
	 * there is no such item)
	 * @param t
	 * @return
	 */
	public int count(T t) {
		if (!counts.containsKey(t)) {
			return 0;
		}
		return counts.get(t);
	}
	
	/**
	 * Removes one of the given items
	 * @param t
	 * @return the number of items left
	 */
	public int remove(T t) {
		int c = count(t);
		if (c <= 0)
			return 0;
		counts.put(t, c--);
		return c;
	}
	
	/**
	 * Removes all of the given item by
	 * setting its count to 0.
	 * @param t
	 */
	public void removeAll(T t) {
		if (counts.containsKey(t))
			counts.put(t, 0);
	}
	
	/**
	 * Clears this table and all of its counts, 
	 * resetting everything to 0.
	 */
	public void clear() {
		counts.clear();
	}
}
